﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevelopStudio.Basic;
using DevelopStudio.Control.Basic;
using System.Threading;

namespace DevelopStudio.Control.Commit
{
    public partial class BugsPageControl : ChangelistPageControl
    {

        private const string ActionBugsTitle = "ActionBugsTitle";

        private const string AssignedToTitle = "AssignedToTitle";

        public BugsPageControl()
        {
            InitializeComponent();
        }

        public BugsPageControl(ChangelistInfo changelistInfo)
            : base(changelistInfo)
        {
            InitializeComponent();
        }

        public override void InitializePageControl()
        {
            base.InitializePageControl();

            string openBy = string.Empty;

            foreach (BugInfo bugInfo in this.ChangelistInfo.BugInfos)
            {
                openBy = bugInfo.Author.ID;
                this.listView1.Items.Add(new ListViewItem(new string[] { bugInfo.ID.ToString(), bugInfo.Subject, bugInfo.Description }) { Tag = bugInfo });
            }

            this.textBoxComment.Text = this.ChangelistInfo.Comment;

            this.comboBoxAssignedTo.DataSource = Utility.Settings.Redmine.Members.OrderByDescending(o => o.ResolvedFrequency).ThenBy(o => o.Name).ToList();
            this.comboBoxAssignedTo.DisplayMember = "Name";
            this.comboBoxAssignedTo.ValueMember = "ID";

            if (string.IsNullOrEmpty(openBy) == false)
            {
                this.comboBoxAssignedTo.SelectedValue = openBy;
            }
            else
            {
                this.comboBoxAssignedTo.SelectedValue = Utility.Settings.MyInfo.ID;
            }
        }

        public override bool ValidatePage()
        {
            SearchBugs searchBugs = Utility.GetSearchBugs(Utility.Settings.MyInfo.ID);
            Utility.UpdateChangelistBugs(this.ChangelistInfo, searchBugs);

            string message;
            BugInfo[] invalidBugs = this.ChangelistInfo.BugInfos.Where(
                o => Utility.IsOpenBugStatus(o, out message) == false ).ToArray();

            StringBuilder warningMessage = new StringBuilder();

            if (invalidBugs.Length > 0)
            {
                warningMessage.AppendLine(Properties.Resources.ErrorNoSupportResolvedBugHeadline);

                foreach (BugInfo var in invalidBugs)
                {
                    warningMessage.AppendLine(string.Format(Properties.Resources.ErrorNoSupportResolvedBug, var.ID, var.Status.Name));
                }

                if (MessageBox.Show(warningMessage.ToString(), this.ParentForm.Text, MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return false;
                }
            }

            return base.ValidatePage();
        }

        public override void OnAddSummary(SummaryRequestHandler handler)
        {
            base.OnAddSummary(handler);

            this.AddAction(ActionBugsTitle, Properties.Resources.ActionContentAssignedBugsTitle);

            foreach (ListViewItem var in this.listView1.Items)
            {
                this.AddActionDetailMessage(ActionBugsTitle, var.SubItems[0].Text + " " + var.SubItems[1].Text);
            }

            this.AddAction(string.Empty, string.Empty);

            this.AddAction(AssignedToTitle, Properties.Resources.ActionContentAssignedToTitle);

            if (this.checkBoxResolvedBug.Checked == true)
            {
                this.AddActionDetailMessage(AssignedToTitle, string.Format(Properties.Resources.IsResolved, Properties.Resources.Yes));
                this.AddActionDetailMessage(AssignedToTitle, string.Format(Properties.Resources.AssignedTo, ((MemberInfo)this.comboBoxAssignedTo.SelectedItem).Name));
            }
            else
            {
                this.AddActionDetailMessage(AssignedToTitle, string.Format(Properties.Resources.IsResolved, Properties.Resources.No));
            }

            this.AddAction(string.Empty, string.Empty);
        }

        public override void ApplyChanges()
        {
            base.ApplyChanges();

            string message;
            this.ChangelistInfo.IsResovledBugs = this.checkBoxResolvedBug.Checked;

            if (this.checkBoxResolvedBug.Checked == true)
            {
                foreach (BugInfo var in this.ChangelistInfo.BugInfos)
                {
                    if (Utility.IsOpenBugStatus(var, out message) == true)
                    {
                        IdNamePair status = new IdNamePair()
                        {
                            ID = ((int)AppEnum.BugStatus.Resolved).ToString(),
                            Name = AppEnum.GetDescription(typeof(AppEnum.BugStatus), AppEnum.BugStatus.Resolved)
                        };

                        var.Status = status;
                    }

                    MemberInfo member = this.comboBoxAssignedTo.SelectedItem as MemberInfo;

                    IdNamePair assignedTo = new IdNamePair()
                    {
                        ID = member.ID,
                        Name = member.Name
                    };

                    var.AssignedTo = assignedTo;
                }

                Utility.Settings.Redmine.Members.Find(o => o.ID == (string)this.comboBoxAssignedTo.SelectedValue).AutoResolvedFrequency();
            }

            Utility.SaveEnvironmentSettings();
        }

        public override bool TestPostChanges()
        {
            Thread.Sleep(2000);
            this.UpdateActionStatus(ActionBugsTitle, SmsSummaryAction.ActionStatus.CompleteWithWarnings);
            this.AddActionWarningMessage(ActionBugsTitle, "解决bug失败，请检查网络配置！");
            return false;

            //this.UpdateActionStatus(ActionBugsTitle, SmsSummaryAction.ActionStatus.CompleteWithSuccess);

            //return base.TestPostChanges();
        }

        public override bool PostApply()
        {
            bool hasError = false;

            foreach (BugInfo var in this.ChangelistInfo.BugInfos)
            {
                if (var.Status.ID != ((int)AppEnum.BugStatus.Created).ToString() &&
                    var.Status.ID != ((int)AppEnum.BugStatus.Fixing).ToString() &&
                    var.Status.ID != ((int)AppEnum.BugStatus.Reopen).ToString() &&
                    this.ChangelistInfo.IsResovledBugs == true)
                {
                }

                if (var.UpdateRedmine(this.ChangelistInfo, AppEnum.ChangelistStatus.CommitedButWaiting) == true)
                {
                }
                else
                {
                    hasError = true;
                    this.AddActionWarningMessage(ActionBugsTitle, string.Format(Properties.Resources.CommitErrorMessage, string.Format(Properties.Resources.ErrorUpdateBugs, var.ID)));
                }
            }


            if (hasError == true)
            {
                this.UpdateActionStatus(ActionBugsTitle, SmsSummaryAction.ActionStatus.CompleteWithWarnings);
                this.UpdateActionStatus(AssignedToTitle, SmsSummaryAction.ActionStatus.CompleteWithWarnings);
            }
            else
            {
                this.UpdateActionStatus(ActionBugsTitle, SmsSummaryAction.ActionStatus.CompleteWithSuccess);
                this.UpdateActionStatus(AssignedToTitle, SmsSummaryAction.ActionStatus.CompleteWithSuccess);
            }

            return base.PostApply();
        }

        private void checkBoxResolvedBug_CheckedChanged(object sender, EventArgs e)
        {
            this.comboBoxAssignedTo.Enabled = this.checkBoxResolvedBug.Checked;
        }
    }
}
